// 用户状态管理
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 安全地从localStorage读取数据
  const getStoredUserId = () => {
    try {
      const stored = localStorage.getItem('userId')
      return stored || ''
    } catch (error) {
      console.error('读取userId失败:', error)
      return ''
    }
  }

  const getStoredToken = () => {
    try {
      const stored = localStorage.getItem('token')
      return stored || ''
    } catch (error) {
      console.error('读取token失败:', error)
      return ''
    }
  }

  const getStoredUserInfo = () => {
    try {
      const stored = localStorage.getItem('userInfo')
      return stored ? JSON.parse(stored) : {}
    } catch (error) {
      console.error('读取userInfo失败:', error)
      return {}
    }
  }

  const token = ref(getStoredToken())
  const userId = ref(getStoredUserId())
  const userInfo = ref(getStoredUserInfo())

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    try {
      localStorage.setItem('token', newToken)
    } catch (error) {
      console.error('保存token失败:', error)
    }
  }

  // 设置用户ID
  const setUserId = (id) => {
    userId.value = id
    try {
      localStorage.setItem('userId', id)
    } catch (error) {
      console.error('保存userId失败:', error)
    }
  }

  // 设置用户信息
  const setUserInfo = (info) => {
    userInfo.value = info
    try {
      localStorage.setItem('userInfo', JSON.stringify(info))
      
      // 如果用户信息中包含ID，也设置userId
      if (info.id) {
        setUserId(info.id.toString())
      }
    } catch (error) {
      console.error('保存userInfo失败:', error)
    }
  }

  // 检查是否已登录
  const isLoggedIn = () => {
    return !!(token.value && userId.value)
  }

  // 获取用户名
  const getUsername = () => {
    return userInfo.value.userName || userInfo.value.username || ''
  }

  // 登出
  const logout = () => {
    token.value = ''
    userId.value = ''
    userInfo.value = {}
    try {
      // 清除 localStorage
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('hasWatchedIntroVideo') // 清除视频播放状态
      
      // 清除 sessionStorage
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('userInfo')
    } catch (error) {
      console.error('清除存储数据失败:', error)
    }
  }

  // 调试信息
  const getDebugInfo = () => {
    return {
      token: token.value,
      userId: userId.value,
      userInfo: userInfo.value,
      isLoggedIn: isLoggedIn(),
      localStorage: {
        token: localStorage.getItem('token'),
        userId: localStorage.getItem('userId'),
        userInfo: localStorage.getItem('userInfo')
      }
    }
  }

  return {
    token,
    userId,
    userInfo,
    setToken,
    setUserId,
    setUserInfo,
    logout,
    isLoggedIn,
    getUsername,
    getDebugInfo
  }
}) 